package com.example.easyesdemo.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.easyesdemo.entity.OrderTest;
import com.example.easyesdemo.mapper.OrderTestEsMapper;
import lombok.AllArgsConstructor;
import org.dromara.easyes.core.conditions.select.LambdaEsQueryWrapper;
import org.dromara.easyes.core.core.EsWrappers;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;

/**
 * @author benjamin_5
 * @Description
 * @date 2023/8/6
 */
@RestController
@AllArgsConstructor
@RequestMapping("order")
public class OrderEsController {

    private final OrderTestEsMapper orderEsMapper;

    @GetMapping("search")
    public String search(){
        SearchResponse search = orderEsMapper.search(EsWrappers.lambdaQuery(OrderTest.class).groupBy(OrderTest::getStatus));

        // 包装查询结果
        Aggregations aggregations = search.getAggregations();
        Terms terms = (Terms)aggregations.asList().get(0);
        List<? extends Terms.Bucket> buckets = terms.getBuckets();
        HashMap<String,Long> statusRes = new HashMap<>();
        buckets.forEach(bucket -> {
            statusRes.put(bucket.getKeyAsString(),bucket.getDocCount());
        });
        System.out.println("---聚合结果---");
        System.out.println(statusRes);
        return statusRes.toString();
    }
}
